import { loginAPI, logout, getUserAPI } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    user: null,
  };
};

const state = getDefaultState();

const mutations = {
  SET_USER: (state, user) => {
    state.user = user;
  },
  SET_TOKEN: (state, token) => {
    setToken(token);
    state.token = token;
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
};

const actions = {
  updateUserInfo({ commit }, newUserInfo) {
    commit("SET_USER", newUserInfo);
  },
  // user login
  async login({ commit }, userInfo) {
    const { loginId, loginPwd, captcha, remember } = userInfo;
    const res = await loginAPI({
      loginId: loginId.trim(),
      loginPwd: loginPwd,
      captcha: captcha,
      remember: remember,
    });
    if (typeof res === "string") {
      const { msg } = JSON.parse(res);
      return msg;
    } else {
      const { data } = res;
      if (!data) {
        return "未获取到用户信息，请检查账户重新登录";
      }
      commit("SET_USER", data);
    }
  },

  // get user info
  async getUserInfo({ commit }) {
    const res = await getUserAPI();
    if (typeof res === "string") {
      const { msg } = JSON.parse(res);
      resetRouter();
      removeToken();
      commit("RESET_STATE");
      return msg;
    } else {
      const { data } = res;
      if (!data) {
        resetRouter();
        removeToken();
        commit("RESET_STATE");
        return "未获取到用户信息，请检查账户重新登录";
      }
      commit("SET_USER", data);
    }
  },

  // user logout
  logout({ commit, state }) {
    removeToken(); // must remove  token  first
    resetRouter();
    commit("RESET_STATE");
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
